package com.atguigui.leetcode;

/**
 * 执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
 * 内存消耗：39.1 MB, 在所有 Java 提交中击败了24.46%的用户
 * 965.单值二叉树
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/5/24 21:53
 */
public class P965UnivaluedBinaryTree {
    public static void main(String[] args) {
        Solution solution = new P965UnivaluedBinaryTree().new Solution();
        // TO TEST
    }

    class Solution {

        private boolean result = true;


        public boolean isUnivalTree(TreeNode root) {
            int value = root.val;

            dfs(root.left, value);
            dfs(root.right, value);

            return result;
        }

        /**
         * 递归循环遍历
         *
         * @param root
         * @param value 初始的值
         */
        private void dfs(TreeNode root, int value) {
            // 只要result变为true就一路返回
            if (!result || root == null) {
                return;
            }

            if (root.val != value) {
                result = false;
                return;
            }
            // 递归循环遍历左边
            dfs(root.left, value);
            // 递归循环遍历右边
            dfs(root.right, value);
        }


    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
